package com.tywj.lib.core.common.application

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Process
import androidx.multidex.MultiDex
import com.tywj.lib.core.common.util.AppUtil
import com.blankj.utilcode.util.Utils
import net.danlew.android.joda.JodaTimeAndroid

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/7
 *     desc   : lib Application
 *     version: 1.0.0
 * </pre>
 */
abstract class LibApplication : Application() {

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)

        // 解决方法数超过65536限制
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()

        if (shouldInit(this@LibApplication)) {
            // 这里主要是在处理多进程的时候，只初始化一次
            initLibrary()
        }

    }

    private fun initLibrary() {
        AppUtil.context = this
        AppUtil.isRelease = isRelease()

        Utils.init(this)

        JodaTimeAndroid.init(this)
    }

    /**
     * 判断是否能初始化数据，主要是用于App采用多线程时，只初始化一次数据
     */
    private fun shouldInit(context: Context): Boolean {
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val processInfoList = am.runningAppProcesses
        val mainProcessName = context.packageName
        val myPid = Process.myPid()
        return processInfoList.any { it.pid == myPid && it.processName == mainProcessName }
    }

    /**
     * 当前运行环境是否为正式环境
     */
    protected open fun isRelease(): Boolean = false

}